package net.dgg.rz.production.service;

import com.alibaba.fastjson.JSONArray;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.rz.common.base.service.BaseService;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.service.CommonMangerExtService;
import net.dgg.rz.common.utils.StringUtils;
import net.dgg.rz.common.utils.ValidateUtils;
import net.dgg.rz.production.dao.ProductOrderDao;
import net.dgg.rz.production.dao.ProductOrderWorkLoadDao;
import net.dgg.rz.production.entity.ProductOrder;
import net.dgg.rz.production.entity.ProductOrderFieldWorkLoad;
import net.dgg.rz.production.entity.ProductOrderWorkLoad;
import net.dgg.rz.production.entity.dto.WorkLoadDto;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.treebook.entity.TreeBook;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 生产订单工作录入
 * Created by sdx on 2019/09/25.
 */
@Service
public class ProductOrderWorkLoadService extends BaseService {


    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private UserService userService;

    @Autowired
    private ProductOrderDao productOrderDao;

    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    private CommonMangerExtService commonMangerExtService;

    @Autowired
    private ProductOrderWorkLoadDao productOrderWorkLoadDao;

    /**
     * 新增页面-外勤工作量获取基础数据
     * @param scOrderId
     * @param recordType
     * @return
     */
    public WorkLoadDto findModel(Long scOrderId,String loginName,Integer recordType ) {
        WorkLoadDto workLoadDto = new WorkLoadDto();
        //如果传递过来用户ID那么通过查询获取用户信息，如果没有则获取当前登录用户
        UserEntity userEntity = null;
        if(null != loginName){
            userEntity = userService.findUserByLoginName(loginName);
        }else{
            userEntity =  sessionManager.getCurrentUser();
        }
        workLoadDto.setUserEntity(userEntity);
        //获取当前生产单
        ValidateUtils.strNotEmpty(scOrderId, CommonExcption.class, "生产子订单id不能为空");
        ProductOrder order = productOrderDao.selectByPrimaryKey(scOrderId);
        workLoadDto.setOrder(order);
        Map blqyParams = new HashMap();
        Map bllxParams = new HashMap();
        List<ProductOrderWorkLoad> blqyList = null;
        List<ProductOrderWorkLoad> bllxList = null;
        if(recordType == 1){
            //获取当前事业部办理区域
            blqyParams.put("orgId",order.getProductOrgId());
            blqyParams.put("status",1L);
            blqyList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(blqyParams);
            workLoadDto.setBlqyList(blqyList);
            //获取当前事业部办理类型(权证)
            bllxParams.put("orgId",order.getProductOrgId());
            bllxParams.put("status",2L);
            bllxList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(bllxParams);
            workLoadDto.setBllxList(bllxList);
        }else if(recordType == 2){
            //获取当前事业部办理类型（资料）
            bllxParams.put("status",3L);
            bllxList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(bllxParams);
            workLoadDto.setBllxList(bllxList);
        }
        return workLoadDto;
    }

    /**
     * 新增外勤工作量数据
     * @param recordType
     * @param userId
     * @param scOrderId
     * @param orgId
     * @param pofwlJson
     */
    @Transactional(rollbackFor = Exception.class)
    public void addFieldWorkLoad(Long recordType, Long userId, Long scOrderId, Long orgId, String pofwlJson){
        //如果传递过来用户ID那么通过查询获取用户信息，如果没有则获取当前登录用户
        UserEntity userEntity = null;
        if(null != userId){
             userEntity = userService.findUserById(userId);
        }else{
            userEntity =  sessionManager.getCurrentUser();
        }
        //TODO 判断是不是自己所在事业部的订单
        //获取当前登录用户的所在事业部
        Map orgMap = commonMangerExtService.findBusDeptById(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(orgMap, CommonExcption.class, "登录用户所属事业部信息为空！");
        Long sybId =  Long.parseLong(orgMap.get("id").toString());
        //TODO 当事业部为字典所配置的事业部时，不判断是否是自己所在事业部
        List<TreeBook> treeBooks = commonMangerExtService.queryTreeBookListByCode(ScProductConstant.RZSC_ORG_PERMISSION, 1, null);
        List<String> idList = treeBooks.stream().map(treeBook -> treeBook.getExt1()).collect(Collectors.toList());
        if(!idList.contains(orgId.toString())){
            //获取当前登录用户的所在事业部
            if(!sybId.equals(orgId)){
                throw new CommonExcption("不允许操作不是自己所在事业部的数据！");
            }
        }
        //TODO 获取当前生产单——多条记录，生产单数据是一致
        ValidateUtils.strNotEmpty(scOrderId, CommonExcption.class, "生产子订单id不能为空");
        ProductOrder order = productOrderDao.selectByPrimaryKey(scOrderId);
        //转换json对象为自己需要的实体对象
        List<ProductOrderFieldWorkLoad> pofwlList =  JSONArray.parseArray(pofwlJson, ProductOrderFieldWorkLoad.class);
        //TODO 根据输入的记录条数储存
        if(null != pofwlList && pofwlList.size() > 0){
            for(ProductOrderFieldWorkLoad pofwl :pofwlList){
                ProductOrderFieldWorkLoad p = new ProductOrderFieldWorkLoad();
                //根据输入的记录类型分别储存各自的参数
                if(null != recordType){
                    if(recordType == 1L){
                        //权证工作录入
                        if(null != pofwl.getHandleArea()){
                            p.setHandleArea(pofwl.getHandleArea());//办理区域
                            //TODO 做储存时把办理区域的value值做冗余储存，便于查询
                            Map blqyParams = new HashMap();
                            blqyParams.put("orgId",order.getProductOrgId());
                            blqyParams.put("status",1L);
                            blqyParams.put("handleCode",pofwl.getHandleArea());
                            List<ProductOrderWorkLoad> blqyList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(blqyParams);
                            if(null != blqyList && blqyList.size() > 0){
                                p.setHandleAreaValue(blqyList.get(0).getHandleValue());
                            }
                        }
                        if(null != pofwl.getHandleType()){
                            p.setHandleType(pofwl.getHandleType());//办理类型
                            //TODO 做储存时把办理类型的value值也做冗余储存，便于查询
                            Map bllxParams = new HashMap();
                            bllxParams.put("orgId",order.getProductOrgId());
                            bllxParams.put("status",2L);
                            bllxParams.put("handleCode",pofwl.getHandleType());
                            List<ProductOrderWorkLoad> bllxList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(bllxParams);
                            if(null != bllxList && bllxList.size() > 0){
                                p.setHandleTypeValue(bllxList.get(0).getHandleValue());
                            }
                        }
                        if(StringUtils.isNotEmpty(pofwl.getHandlePlace())){
                            p.setHandlePlace(pofwl.getHandlePlace());//办理地点
                        }
                    }else if(recordType == 2L){
                        //资料工作录入
                        if(StringUtils.isNotEmpty(pofwl.getBank())){
                            p.setBank(pofwl.getBank());//银行
                        }
                        if(null != pofwl.getHandleType()){
                            p.setHandleType(pofwl.getHandleType());//办理类型
                            //TODO 做储存时把办理类型的value值做冗余储存，便于查询
                            Map bllxParams = new HashMap();
                            bllxParams.put("status",3L);
                            bllxParams.put("handleCode",pofwl.getHandleType());
                            List<ProductOrderWorkLoad> bllxList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(bllxParams);
                            if(null != bllxList && bllxList.size() > 0){
                                p.setHandleTypeValue(bllxList.get(0).getHandleValue());
                            }
                        }
                        if(null != pofwl.getHandleNum()){
                            p.setHandleNum(pofwl.getHandleNum());//办理数量
                        }
                    }else if(recordType == 3L){
                        //评估工作录入
                        if(StringUtils.isNotEmpty(pofwl.getAssessmentCompany())){
                            p.setAssessmentCompany(pofwl.getAssessmentCompany());//评估公司
                        }
                        if(StringUtils.isNotEmpty(pofwl.getBank())){
                            p.setBank(pofwl.getBank());//银行
                        }
                    }else if(recordType == 4L){
                        //驻点工作录入
                        //判断是否放款，如果未放款那么就不能够保存驻点工作记录
                        if(order.getIsLoan() == 1){
                            if(null != pofwl.getLoanTime()){
                                p.setLoanTime(pofwl.getLoanTime());//放款日期
                            }
                            if (null != pofwl.getLoanMoney()) {
                                p.setLoanMoney(pofwl.getLoanMoney());//放款金额
                            }
                            if(StringUtils.isNotEmpty(pofwl.getProductName())){
                                p.setProductName(pofwl.getProductName());//产品名称

                            }
                            if(StringUtils.isNotEmpty(pofwl.getChannelName())){
                                p.setChannelName(pofwl.getChannelName());//渠道名称
                            }
                        }else{
                            throw new CommonExcption("驻点工作录入必须是已放款的订单！");
                        }
                    }
                }else{
                    throw new CommonExcption("选择类型有误！请重新选择工作量录入的类型！");
                }
                //TODO 所有类型都需要的参数
                p.setId(DggKeyWorker.nextId());
                p.setScProductOrderId(order.getId());//生产子订单ID
                p.setScProductOrderNo(order.getScProductOrderNo());//生产子订单编号
                p.setOrderId(order.getOrderId());//销售主订单ID
                p.setOrderNo(order.getOrderNo());//销售主订单编号
                p.setCustomerId(order.getCustomerId());//客户ID
                p.setCustomerNo(order.getCustomerNo());//客户编号
                p.setCustomerName(order.getCustomerName());//客户名字
                p.setFlowUserId(order.getFlowUserId());//流程人员ID
                p.setFlowUserName(order.getFlowUserName());//流程人员名字
                p.setProductOrgId(order.getProductOrgId());//生产所属ID
                p.setProductOrgName(order.getProductOrgName());//生产所属名字
                p.setManageUserId(userEntity.getId());//办理人员ID
                p.setManageUserName(userEntity.getRealName()+userEntity.getLoginName());//办理人员名字
                if(null != pofwl.getHandleTime()){
                    p.setHandleTime(pofwl.getHandleTime());//办理时间
                }
                if(StringUtils.isNotEmpty(pofwl.getRemark())){
                    p.setRemark(pofwl.getRemark());//备注
                }
                p.setRecordType(recordType);//记录类型 1 权证工作记录 2 资料工作记录 3 评估工作记录 4 驻点工作记录
                saveOpt(p,userEntity);
                productOrderWorkLoadDao.insert(p);
            }
        }else{
            throw new CommonExcption("请至少输入一条记录！");
        }
    }

    /**
     * 获取外勤工作量列表数据
     * @param params
     * @return
     */
    public List<ProductOrderFieldWorkLoad> findProductOrderFieldWorkLoadWithPage(Map params){
        //办理时间
        if(StringUtils.isNotEmpty(String.valueOf(params.get("handleTime")))){
            String handleTime=String.valueOf(params.get("handleTime"));
            String handleTimeStart=handleTime.substring(0,handleTime.indexOf("~"));
            handleTimeStart= handleTimeStart.trim();
            String handleTimeEnd = handleTime.substring(handleTime.indexOf("~") + 1);
            handleTimeEnd= handleTimeEnd.trim();
            params.put("handleTimeStart", handleTimeStart);
            params.put("handleTimeEnd", handleTimeEnd);
        }
        List<ProductOrderFieldWorkLoad> list = productOrderWorkLoadDao.findProductOrderFieldWorkLoadWithPage(params);
        //驻点工作量录入的数据根据生产单的为准。但生产单为空则取工作量录入时的数据
        if(null != list && list.size() > 0){
            for(ProductOrderFieldWorkLoad p : list){
                //转换数据
                conversion(p);
            }
        }
        //翻译字段
        String[] transColum = {"status"};
        list = translateUtil.translateList(transColum, list);
        return list;
    }

    /**
     * 编辑页面-获取当前选中外勤工作量数据
     * @param id
     * @return
     */
    public WorkLoadDto findProductOrderFieldWorkLoad(Long id,String loginName){
        WorkLoadDto workLoadDto = new WorkLoadDto();
        Map params = new HashMap();
        params.put("id",id);
        ProductOrderFieldWorkLoad productOrderFieldWorkLoad = productOrderWorkLoadDao.findProductOrderFieldWorkLoad(params);
        //转换数据
        conversion(productOrderFieldWorkLoad);
        workLoadDto.setProductOrderFieldWorkLoad(productOrderFieldWorkLoad);
        //如果传递过来用户ID那么通过查询获取用户信息，如果没有则获取当前登录用户
        UserEntity userEntity = null;
        if(null != loginName){
            userEntity = userService.findUserByLoginName(loginName);
        }else{
            userEntity =  sessionManager.getCurrentUser();
        }
        workLoadDto.setUserEntity(userEntity);
        if(null != productOrderFieldWorkLoad){
            if(productOrderFieldWorkLoad.getRecordType() == 1L){
                //获取当前事业部办理区域
                Map blqyParams = new HashMap();
                blqyParams.put("orgId",productOrderFieldWorkLoad.getProductOrgId());
                blqyParams.put("status",1L);
                List<ProductOrderWorkLoad> blqyList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(blqyParams);
                workLoadDto.setBlqyList(blqyList);
                //获取当前事业部办理类型(权证)
                Map bllxParams = new HashMap();
                bllxParams.put("orgId",productOrderFieldWorkLoad.getProductOrgId());
                bllxParams.put("status",2L);
                List<ProductOrderWorkLoad> bllxList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(bllxParams);
                workLoadDto.setBllxList(bllxList);
            }
            if(productOrderFieldWorkLoad.getRecordType() == 2L){
                //获取当前事业部办理类型（资料）
                Map bllxParams = new HashMap();
                bllxParams.put("status",3L);
                List<ProductOrderWorkLoad> bllxList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(bllxParams);
                workLoadDto.setBllxList(bllxList);
            }
        }
        return workLoadDto;
    }

    /**
     * 编辑外勤工作量数据
     * @param pofwlJson
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFieldWorkLoad(String loginName,String pofwlJson){
        //将接收的json对象转换成自己需要的实体对象
        ProductOrderFieldWorkLoad pofwl =  JSONArray.parseObject(pofwlJson, ProductOrderFieldWorkLoad.class);
        if(null != pofwl){
            //如果传递过来用户ID那么通过查询获取用户信息，如果没有则获取当前登录用户
            UserEntity userEntity = null;
            if(null != loginName){
                userEntity = userService.findUserByLoginName(loginName);
            }else{
                userEntity =  sessionManager.getCurrentUser();
            }
            if(!userEntity.getId().equals(pofwl.getManageUserId())){
                throw new CommonExcption("不允许修改不是自己新增的数据！");
            }
            //TODO 主要处理工作量录入中的字典值，做办理类型和办理区域的value值冗余
            if(pofwl.getRecordType() == 1L){
                Map blqyParams = new HashMap();
                blqyParams.put("orgId",pofwl.getProductOrgId());
                blqyParams.put("status",1L);
                blqyParams.put("handleCode",pofwl.getHandleArea());
                List<ProductOrderWorkLoad> blqyList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(blqyParams);
                if(null != blqyList && blqyList.size() > 0){
                    pofwl.setHandleAreaValue(blqyList.get(0).getHandleValue());
                }
                Map bllxParams = new HashMap();
                bllxParams.put("orgId",pofwl.getProductOrgId());
                bllxParams.put("status",2L);
                bllxParams.put("handleCode",pofwl.getHandleType());
                List<ProductOrderWorkLoad> bllxList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(bllxParams);
                if(null != bllxList && bllxList.size() > 0){
                    pofwl.setHandleTypeValue(bllxList.get(0).getHandleValue());
                }
            }
            if(pofwl.getRecordType() == 2L){
                Map bllxParams = new HashMap();
                bllxParams.put("status",3L);
                bllxParams.put("handleCode",pofwl.getHandleType());
                List<ProductOrderWorkLoad> bllxList = productOrderWorkLoadDao.findProductOrderWorkLoadByOrgId(bllxParams);
                if(null != bllxList && bllxList.size() > 0){
                    pofwl.setHandleTypeValue(bllxList.get(0).getHandleValue());
                }
            }
            //设置修改人信息
            updateOpt(pofwl,userEntity);
            productOrderWorkLoadDao.updateByPrimaryKey(pofwl);
        }else{
            throw new CommonExcption("操作失败！请联系管理员！");
        }
    }

    /**
     * 删除外勤工作量数据
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteFieldWorkLoad(String loginName,Long id){
        if(null != id){
            Map params = new HashMap();
            params.put("id",id);
            ProductOrderFieldWorkLoad pofwl = productOrderWorkLoadDao.findProductOrderFieldWorkLoad(params);
            //如果传递过来用户ID那么通过查询获取用户信息，如果没有则获取当前登录用户
            UserEntity userEntity = null;
            if(null != loginName){
                userEntity = userService.findUserByLoginName(loginName);
            }else{
                userEntity =  sessionManager.getCurrentUser();
            }
            if(!userEntity.getId().equals(pofwl.getManageUserId())){
                throw new CommonExcption("不允许删除不是自己新增的数据！");
            }
            pofwl.setState(1);
            updateOpt(pofwl,userEntity);
            productOrderWorkLoadDao.updateByPrimaryKey(pofwl);
        }else{
            throw new CommonExcption("操作失败！请联系管理员！");
        }
    }


    /**
     * 数据转换-生产单中有这些数据是使用生产单中的数据
     * @param productOrderFieldWorkLoad
     * @return
     */
    public ProductOrderFieldWorkLoad conversion(ProductOrderFieldWorkLoad productOrderFieldWorkLoad){
        //生产事业部
        if(StringUtils.isNotEmpty(productOrderFieldWorkLoad.getProductOrgNameOrder())){
            productOrderFieldWorkLoad.setProductOrgName(productOrderFieldWorkLoad.getProductOrgNameOrder());
        }
        //当是驻点工作量时下列字段也要使用生产单中数据
        if(productOrderFieldWorkLoad.getRecordType() == 4L){
            //放款时间
            if(null != productOrderFieldWorkLoad.getLoanTimeOrder()){
                productOrderFieldWorkLoad.setLoanTime(productOrderFieldWorkLoad.getLoanTimeOrder());
            }
            //放款金额
            if(null != productOrderFieldWorkLoad.getLoanMoneyOrder()){
                productOrderFieldWorkLoad.setLoanMoney(productOrderFieldWorkLoad.getLoanMoneyOrder());
            }
            //产品名称
            if(StringUtils.isNotEmpty(productOrderFieldWorkLoad.getProductNameOrder())){
                productOrderFieldWorkLoad.setProductName(productOrderFieldWorkLoad.getProductNameOrder());
            }
            //渠道名称
            if(StringUtils.isNotEmpty(productOrderFieldWorkLoad.getChannelNameOrder())){
                productOrderFieldWorkLoad.setChannelName(productOrderFieldWorkLoad.getChannelNameOrder());
            }
        }
        return productOrderFieldWorkLoad;
    }
}
